package leetcode.practice;

/**
 * 21. 合并两个有序链表
 */
public class MergeTwoLists {

    public ListNode merge(ListNode head1, ListNode head2) {

        if (head1 == null && head1 == null) {
            return null;
        }
        if (head1 == null) {
            return head2;
        }
        if (head2 == null) {
            return head1;
        }

        ListNode dummyNode = new ListNode();
        ListNode node = dummyNode;
        while (head1 != null && head2 != null) {
            if (head1.val == head2.val) {
                node.next = head1;
                head1 = head1.next;
                node = node.next;

                node.next = head2;
                head2 = head2.next;
                node = node.next;
            } else if (head1.val < head2.val) {

                node.next = head1;
                head1 = head1.next;
                node = node.next;
            } else {
                node.next = head2;
                head2 = head2.next;
                node = node.next;
            }
        }

        node.next = head1 != null ? head1 : head2;

        return dummyNode.next;
    }

    class ListNode {
        int val;
        ListNode next;
    }
}


